package com.qlylkj.lbk.base

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider

/**
 *    author : duanguosen
 *    date   : 2019/11/25
 *    desc   :
 */
abstract class BaseVMFragment<VM : BaseViewModel> : BaseFragment() {

    protected lateinit var mViewModel: VM


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initVM()
        startObserve()
    }

    open fun startObserve() {
        mViewModel.mException.observe(viewLifecycleOwner, Observer { it?.let { onError(it) } })
        mViewModel.mLoginState.observe(viewLifecycleOwner, Observer { it?.let { toLogin() } })
    }

    open fun onError(e: Throwable) {}

    private fun initVM() {
        providerVMClass()?.let {
            mViewModel = ViewModelProvider(this).get(it)
            lifecycle.addObserver(mViewModel)
        }
    }

    open fun providerVMClass(): Class<VM>? = null

    override fun onDestroy() {
        lifecycle.removeObserver(mViewModel)
        super.onDestroy()
    }
}